# cython: language_level=3
import json
from datetime import datetime

from sqlalchemy.orm import Session

from app.models.intra_day_task import IntraDayTask
from app.models.intra_day_task_resource import IntraDayTaskResource
from common.redis import MyRedis


def save_intra_day_task(db: Session, intra_day_task_id, payload: IntraDayTask):
    if intra_day_task_id is None:
        # 新增
        intra_day_task = IntraDayTask(
            task_code=payload.task_code,
            task_name=payload.task_name,
            create_time=datetime.now(),
        )
        db.add(intra_day_task)
    else:
        # 修改
        intra_day_task = db.get(IntraDayTask, intra_day_task_id)
        intra_day_task.task_code = payload.task_code
        intra_day_task.task_name = payload.task_name
        intra_day_task.update_time = datetime.now()
    db.commit()


def save_intra_day_task_resource(db: Session, payload: list[IntraDayTaskResource]):
    db.add_all(payload)
    db.commit()


def update_resource_rtd(resource_id: str, payload: dict, redis: MyRedis):
    """
    更新资源实时数据
    """
    redis.set_rtd(resource_id, json.dumps(payload))


def get_resource_rtd(resource_id: str, redis: MyRedis):
    """
    获取资源实时数据
    """
    rtd = redis.get_rtd(resource_id)
    return json.loads(rtd) if rtd is not None else None
